<?php
declare(strict_types=1);
namespace App\Controller\zygame;


use App\Controller\AbstractController;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use App\Common\SqlUnion;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Common\User;
use App\Common\DateTime;
use mysql_xdevapi\Statement;
use function Hyperf\Config\config;
use function Hyperf\Stringable\str;

/**
 *  用户信息
 */
#[Controller(prefix:'zygame.aviator')]
class AviatorController extends AbstractController {


    #[Inject]
    protected SqlUnion $SqlUnion;

    protected string $day= '1';
    protected string $month= '2';
    protected string $year= '3';

    /**
     * 逃跑倍率排行榜
     * @return void
     */
    #[RequestMapping(path: 'hugWins')]
    public function hugWins(){
//        $list = Db::connection('readConfig')
//            ->table('aviator_huge_wins')
//            ->selectRaw('id,round,settlement_ratio,bet,escape_ratio,win,name,avatar,time')
//            ->where($this->getTimeWhere($this->request->post('type','1')))//1当天,2=本月,3=本年
//            ->orderBy('escape_ratio','desc')
//            ->forPage(1,20)
//            ->get()
//            ->toArray();

        $list = Db::connection('readConfig')
            ->table('aviator_user')
            ->selectRaw('round_id,bet,settlement_ratio,escape_ratio,win,name,avatar,time')
            ->where($this->getTimeWhere($this->request->post('type','1')))//1当天,2=本月,3=本年
            ->orderBy('escape_ratio','desc')
            ->forPage(1,20)
            ->get()
            ->toArray();
        return $this->response->json($this->getNewList($list));
    }



    /**
     * 最大赢金排行
     * @return void
     */
    #[RequestMapping(path: 'biggestWins')]
    public function biggestWins(){

//        $list = Db::connection('readConfig')
//            ->table('aviator_biggest_wins')
//            ->selectRaw('id,round,settlement_ratio,bet,escape_ratio,win,name,avatar,time')
//            ->where($this->getTimeWhere($this->request->post('type','1')))//1当天,2=本月,3=本年
//            ->orderBy('win','desc')
//            ->forPage(1,20)
//            ->get()
//            ->toArray();

        $list = Db::connection('readConfig')
            ->table('aviator_user')
            ->selectRaw('round_id,bet,settlement_ratio,escape_ratio,win,name,avatar,time')
            ->where($this->getTimeWhere($this->request->post('type','1')))//1当天,2=本月,3=本年
            ->orderBy('win','desc')
            ->forPage(1,20)
            ->get()
            ->toArray();
        return $this->response->json($this->getNewList($list));
    }



    /**
     * 最大倍数排行
     * @return void
     */
    #[RequestMapping(path: 'multipliers')]
    public function multipliers(){

//        $list = Db::connection('readConfig')
//            ->table('aviator_multipliers')
//            ->selectRaw('id,round,settlement_ratio,time')
//            ->where($this->getTimeWhere($this->request->post('type','1')))//1当天,2=本月,3=本年
//            ->orderBy('settlement_ratio','desc')
//            ->forPage(1,20)
//            ->get()
//            ->toArray();

        $list = Db::connection('readConfig')
            ->table('aviator_round')
            ->selectRaw('round as round_id,settlement_ratio,time')
            ->where($this->getTimeWhere($this->request->post('type','1')))//1当天,2=本月,3=本年
            ->orderBy('settlement_ratio','desc')
            ->forPage(1,20)
            ->get()
            ->toArray();
        return $this->response->json($this->getNewList($list));
    }

    /**
     * 详细数据
     * @return void
     */
    #[RequestMapping(path: 'details')]
    public function details(){
        $round_id = $this->request->post('round_id','0');
        $type = $this->request->post('type','1'); // 1 = Top排行榜详情,2=下注记录详情(真实)

        return $this->response->json($type == 1 ? $this->getTopDetails($round_id) : $this->getBetDetails($round_id));
    }


    /**
     * 得到Top排行榜详情
     * @param $round_id
     * @return \Hyperf\Database\Model\Model|\Hyperf\Database\Query\Builder|object|null
     */
    private function getTopDetails($round_id){
        $aviator_round = Db::connection('readConfig')
            ->table('aviator_round')
            ->selectRaw('server_seed,hash,hex,deci,details')
            ->where('round',$round_id)
            ->first();
        if($aviator_round){
            $aviator_round['details'] = json_decode($aviator_round['details'],true);
//            $this->logger->error('details:'.json_encode($aviator_round['details']));
            foreach ($aviator_round['details'] as &$value){
                $value['name'] = $this->maskString($value['name']);
            }
        }
        return $aviator_round;
    }

    /**
     * 获取下注详情
     * @param $round_id
     * @return array
     */
    private function getBetDetails($round_id){
        $time = $this->request->post('time',time());
        $game_log = Db::connection('lzmj')
            ->table('game_table_'.date('Ymd',(int)$time))
            ->selectRaw('cards_1,cards_2,cards_3,seed')
            ->where('issue',$round_id)
            ->where('game_type',1514)
            ->first();
        if(!$game_log)return [];
        if(strlen($game_log['seed']) < 106)return [];
        $server_seed = substr($game_log['seed'],0,40);  //服务器种子
        [$details,$hashStr] = $this->getDetails($game_log);
        $hash = hash('sha512', $server_seed.$hashStr);//Hash
        $hex = substr($hash,0,13);//hex
        return  [
            'server_seed' => $server_seed,
            'hash' => $hash,
            'hex' => $hex,
            'deci' => hexdec($hex),
            'details' => $details,
        ];

    }


    /**
     * 获取详情的用户前三排名
     * @return array
     */
    private function getDetails($game_log):array{
        $data = [];
        $hashStr = '';
        $nameStr =  substr($game_log['seed'],80,6); //3个玩家的名字
        $nameStartTag = [0,2,4]; //下面循环key对应的名字截取开始位子
        foreach ([40,60,80] as $key => $value){
            $send = substr($game_log['seed'],$value,20);
            $data[] = [
                'avatar' =>  $this->getAvatar($game_log['cards_'.($key+1)]),
                'name' =>  $this->getUserName(substr($nameStr,$nameStartTag[$key],2)),
                'seed' => $send
            ];
            $hashStr.= $send;
        }
        return [$data,$hashStr];
    }


    /**
     * 获取玩家名称
     * @param  $name 玩家名称
     * @return false|string
     */
    private function getUserName(string $name){
        return substr($name,0,1).'***'.substr($name,1,1);
    }

    /**
     * 获取头像
     * @return int
     */
    private function getAvatar($uid){
        $avatar = min(substr((string)$uid, -2),'72');
        //判断第一个数字是不是0
        if(str_starts_with($avatar, '0'))$avatar = substr($avatar, 1,1);
        return (int)$avatar;
    }


    /**
     * 获取时间条件
     * @param string $type 1当天,2=本月,3=本年
     * @return array[]
     */
    private function getTimeWhere(string $type){
        $time = strtotime('00:00:00');
        return match ($type){
            $this->day => [['time','>=',$time],['time','<=',time()]],
            $this->month => $this->getMonth($time),
            $this->year => $this->getYear($time),
        };
    }


    /**
     * 获取本周的开始结束时间
     * @param  int|string $time
     * @return array[]
     */
    private function getMonth(int|string $time):array{
        [$week_start,] = DateTime::startEndWeekTime($time);
        return [['time','>=',$week_start],['time','<=',time()]];
    }




    /**
     * 获取本周的开始结束时间
     * @param  int|string $time
     * @return array[]
     */
    private function getYear(int|string $time):array{
        [$year_start,] = DateTime::startEndYearTime($time);
        return [['time','>=',$year_start],['time','<=',time()]];
    }

    /**
     * 获取新的列表
     * @param array $list 数据
     * @return array
     */
    private function getNewList(array $list):array{
        if(!$list)return [];
        foreach ($list as $key => &$value){
            $value['timeString'] = date('H:i:s',$value['time']);
            $value['yearString'] = date('d',$value['time']).' '.$this->getMonthEnglish(date('m',$value['time']));
            if(isset($value['name']))$value['name'] = $this->maskString($value['name']);
        }
        return $list;
    }

    /**
     * 每月对应的英文前3个字母
     * @param string $month  对应月份
     * @return string
     */
    private function getMonthEnglish(string $month):string{
        return match ($month){
          '01' => 'Jan',
          '02' => 'Feb',
          '03' => 'Mar',
          '04' => 'Apr',
          '05' => 'May',
          '06' => 'Jun',
          '07' => 'Jul',
          '08' => 'Aug',
          '09' => 'Sep',
          '10' => 'Oct',
          '11' => 'Nov',
          '12' => 'Dec',
        };
    }



    /**
     * 隐藏字符串中间的字符，只保留首尾字符，中间替换为三个星号
     * @param string $input
     * @return string
     */
    private function maskString(string $input): string {
        // 检查字符串长度
        $length = strlen($input);

        // 如果字符串长度小于等于 2，则直接返回原字符串
        if ($length <= 2) {
            return $input;
        }

        // 获取第一个字符和最后一个字符
        $firstChar = $input[0];
        $lastChar = $input[$length - 1];

        // 返回处理后的字符串，中间部分固定为 3 个 *
        return $firstChar . '***' . $lastChar;
    }

}


